from rest_framework import serializers
from .models import AIModel, Tag, Prompt, PromptVersion
from django.db.models import Count


class TagSerializer(serializers.ModelSerializer):
    prompt_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Tag
        fields = ['id', 'name', 'color', 'prompt_count']
        
    def get_prompt_count(self, obj):
        return obj.prompts.count()


class AIModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = AIModel
        fields = ['id', 'name', 'provider', 'description', 'icon', 'is_active']


class PromptVersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PromptVersion
        fields = ['id', 'prompt', 'content', 'version_number', 'created_at']
        read_only_fields = ['version_number', 'created_at']


class PromptListSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)
    ai_model = AIModelSerializer(read_only=True)
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Prompt
        fields = [
            'id', 'title', 'description', 'ai_model', 'tags', 
            'is_public', 'likes_count', 'views_count', 'user_username',
            'created_at', 'updated_at'
        ]


class PromptDetailSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)
    ai_model = AIModelSerializer(read_only=True)
    versions = PromptVersionSerializer(many=True, read_only=True)
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Prompt
        fields = [
            'id', 'title', 'description', 'content', 'ai_model', 'tags',
            'is_public', 'likes_count', 'views_count', 'user_username',
            'created_at', 'updated_at', 'versions'
        ]
        read_only_fields = ['likes_count', 'views_count', 'created_at', 'updated_at']


class PromptCreateUpdateSerializer(serializers.ModelSerializer):
    tags = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all(),
        many=True,
        required=False
    )
    
    class Meta:
        model = Prompt
        fields = [
            'title', 'description', 'content', 'ai_model', 'tags',
            'is_public'
        ]
    
    def create(self, validated_data):
        tags = validated_data.pop('tags', [])
        prompt = Prompt.objects.create(**validated_data)
        
        if tags:
            prompt.tags.set(tags)
            
        # 创建第一个版本
        PromptVersion.objects.create(
            prompt=prompt,
            content=validated_data.get('content', ''),
            version_number=1
        )
        
        return prompt
    
    def update(self, instance, validated_data):
        tags = validated_data.pop('tags', None)
        
        # 检查内容是否变更，如果变更则创建新版本
        old_content = instance.content
        new_content = validated_data.get('content', old_content)
        
        if old_content != new_content:
            # 获取最新版本号并创建新版本
            latest_version = instance.versions.order_by('-version_number').first()
            new_version_number = latest_version.version_number + 1 if latest_version else 1
            
            PromptVersion.objects.create(
                prompt=instance,
                content=new_content,
                version_number=new_version_number
            )
        
        # 更新标签
        if tags is not None:
            instance.tags.set(tags)
        
        # 更新其他字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        instance.save()
        return instance


class TagSerializer(serializers.ModelSerializer):
    """标签序列化器"""
    class Meta:
        model = Tag
        fields = ('id', 'name', 'created_at')
        read_only_fields = ('id', 'created_at')


class AIModelSerializer(serializers.ModelSerializer):
    """AI模型序列化器"""
    class Meta:
        model = AIModel
        fields = ('id', 'name', 'is_active')
        read_only_fields = ('id',)


class PromptVersionSerializer(serializers.ModelSerializer):
    """提示词版本序列化器"""
    class Meta:
        model = PromptVersion
        fields = ('id', 'version', 'content', 'created_at')
        read_only_fields = ('id', 'created_at')


class PromptListSerializer(serializers.ModelSerializer):
    """提示词列表序列化器"""
    tags = TagSerializer(many=True, read_only=True)
    models = AIModelSerializer(many=True, read_only=True)
    
    class Meta:
        model = Prompt
        fields = ('id', 'title', 'version', 'user', 'tags', 'models', 'created_at', 'updated_at')
        read_only_fields = ('id', 'user', 'created_at', 'updated_at')


class PromptDetailSerializer(serializers.ModelSerializer):
    """提示词详情序列化器"""
    tags = TagSerializer(many=True, read_only=True)
    models = AIModelSerializer(many=True, read_only=True)
    versions = PromptVersionSerializer(many=True, read_only=True)
    tag_ids = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all(), 
        many=True, 
        write_only=True,
        required=False
    )
    model_ids = serializers.PrimaryKeyRelatedField(
        queryset=AIModel.objects.all(), 
        many=True, 
        write_only=True,
        required=False
    )
    
    class Meta:
        model = Prompt
        fields = ('id', 'title', 'content', 'version', 'ai_output', 'notes', 
                  'user', 'tags', 'models', 'tag_ids', 'model_ids', 'versions',
                  'created_at', 'updated_at')
        read_only_fields = ('id', 'user', 'created_at', 'updated_at', 'versions')
    
    def create(self, validated_data):
        tag_ids = validated_data.pop('tag_ids', [])
        model_ids = validated_data.pop('model_ids', [])
        
        prompt = Prompt.objects.create(**validated_data)
        
        # 添加标签和模型
        if tag_ids:
            prompt.tags.set(tag_ids)
        if model_ids:
            prompt.models.set(model_ids)
        
        # 创建版本记录
        PromptVersion.objects.create(
            prompt=prompt,
            version=prompt.version,
            content=prompt.content
        )
        
        return prompt
    
    def update(self, instance, validated_data):
        tag_ids = validated_data.pop('tag_ids', None)
        model_ids = validated_data.pop('model_ids', None)
        old_content = instance.content
        old_version = instance.version
        
        # 更新提示词基本信息
        instance = super().update(instance, validated_data)
        
        # 如果内容发生变化，创建新版本
        if 'content' in validated_data and old_content != instance.content:
            PromptVersion.objects.create(
                prompt=instance,
                version=instance.version,
                content=instance.content
            )
        
        # 更新标签和模型
        if tag_ids is not None:
            instance.tags.set(tag_ids)
        if model_ids is not None:
            instance.models.set(model_ids)
        
        return instance


class PromptCopySerializer(serializers.Serializer):
    """提示词复制序列化器"""
    title = serializers.CharField(required=False)
    
    def create(self, validated_data):
        original_prompt = self.context.get('prompt')
        user = self.context.get('user')
        
        # 创建新的提示词副本
        new_title = validated_data.get('title', f"{original_prompt.title} (复制)")
        new_prompt = Prompt.objects.create(
            title=new_title,
            content=original_prompt.content,
            version="1.0",
            ai_output=original_prompt.ai_output,
            notes=original_prompt.notes,
            user=user
        )
        
        # 复制标签和模型
        new_prompt.tags.set(original_prompt.tags.all())
        new_prompt.models.set(original_prompt.models.all())
        
        # 创建版本记录
        PromptVersion.objects.create(
            prompt=new_prompt,
            version=new_prompt.version,
            content=new_prompt.content
        )
        
        return new_prompt